package com.hnx.admin.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hnx.admin.api.service.cache.CacheAPI;
import com.hnx.admin.api.service.login.LoginBeforeValidator;
import com.hnx.admin.redis.RedisCache;
import com.hnx.admin.system.domain.param.user.query.LoginBody;
import com.hnx.admin.system.service.SysConfigService;
import com.hnx.admin.utils.IPUtil;
import com.hnx.admin.web.exception.BlackListException;
import com.hnx.admin.web.exception.CaptchaEmptyException;
import com.hnx.admin.web.exception.CaptchaException;
import com.hnx.admin.web.exception.CaptchaExpireException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/5/29   11:01:49 
描   述： 系统登录前置校验扩展方法
*/
@Service
public record LoginBeforeValidatorImpl(RedisCache redisCache, SysConfigService sysConfigService) implements LoginBeforeValidator, CacheAPI {
    @Override
    public void match(Object key) {
        boolean captchaEnabled = sysConfigService.selectCaptchaEnabled();
        if(captchaEnabled){
            if (key instanceof LoginBody) {
                LoginBody userQuery = (LoginBody) key;
                String verifyKey = captchaKey(userQuery.getUuid());
                String captcha = redisCache.getCacheObject(verifyKey,String.class);
                if(!StringUtils.hasText(userQuery.getCode())){
                    throw new CaptchaEmptyException();
                }
                if (!StringUtils.hasText(captcha)) {
                    throw new CaptchaExpireException();
                }
                if(!captcha.equalsIgnoreCase(userQuery.getCode())){
                    redisCache.deleteObject(verifyKey);
                    throw new CaptchaException();
                }
            }
        }

        String blackIp = sysConfigService.selectConfigByKey("sys.login.blackIPList");
        if(StrUtil.isNotBlank(blackIp)) {
            List<String> list = Arrays.stream(blackIp.split(";")).collect(Collectors.toList());
//            String clientIP = IPUtil.resolveClientIp(ServletUtil.getRequest());
            if(IPUtil.matchIP("127.0.0.1", list)){
                throw new BlackListException();
            }
        }

    }
}
